﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using EasyLibrary.AR.Classes;
using EasyLibrary.AR.Services;

namespace EasyFrota_Mobile
{
    public partial class Percursos : System.Web.UI.Page
    {
        protected Literal litBuildPoly = new Literal();
        protected bool LoadMap;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                IList ViaturaTipoList = new ArrayList();
                var vt = new ViaturaTipo();
                ViaturaTipoList = vt.LoadAll();
                DropDownAdd(ViaturaTipoList);

                IList ViaturaList = new ArrayList();
                var v = new Viatura();
                int id = Convert.ToInt32(Session["IDUtilizadores"]);
                ViaturaList = v.LoadAll(id);
                DropDownAdd2(ViaturaList);
            }
        }

        private void DropDownAdd2(IList viaturaList)
        {
            dropDownVeiculo.Items.Clear();
            dropDownVeiculo.Items.Add(new ListItem("Seleccionar", "0"));
            foreach (Viatura via in viaturaList)
            {
                dropDownVeiculo.Items.Add(new ListItem(via.Matricula, via.Idviatura.ToString()));
            }
        }

        private void DropDownAdd(IList viaturaTipoList)
        {
            dropDrownTipoViatura.Items.Add(new ListItem("Todos", "0"));
            foreach (ViaturaTipo viaTipo in viaturaTipoList)
            {
                dropDrownTipoViatura.Items.Add(new ListItem(viaTipo.TipoViatura, viaTipo.Id.ToString()));
            }
        }

        protected void dropDrownTipoViatura_SelectedIndexChanged(object sender, EventArgs e)
        {
            IList ViaturaList = new ArrayList();
            var v = new Viatura();
            int id = Convert.ToInt32(Session["IDUtilizadores"]);
            ViaturaList = v.LoadAllByCat(id, dropDrownTipoViatura.SelectedItem.ToString());
            DropDownAdd2(ViaturaList);
        }

        protected void dropDownVeiculo_SelectedIndexChanged(object sender, EventArgs e)
        {
            HtmlGenericControl body = (HtmlGenericControl) Page.Master.FindControl("mobileBody");
           // body.Attributes.Add("onload", "initialize();");
            int k = 0;
            double distancia = 0;
            long duracao = 0;
            double consumo = 0;
            var ciPt = new CultureInfo("pt-PT");
            var ciInv = CultureInfo.InvariantCulture;
            Gps g = new Gps();
            StringBuilder sb = new StringBuilder();
            IList<GpsCoordinatesSegment> segments =
                g.GetCoordinatesSegmentFast(int.Parse(dropDownVeiculo.SelectedItem.Value), DateTime.Now.Date,
                                            DateTime.Now.Date.AddDays(1).AddSeconds(-1));

            string[] colors = new string[]
                                  {
                                      "#FF0000",
                                      "#00FF00",
                                      "#0000FF",
                                      "#000000",
                                      "#CCCCCC",
                                      "#FFFF00",
                                      "#FFCC00",
                                      "#8B8682",
                                      "#00FFFF",
                                      "#EE3B3B",
                                      "#CCFF99",
                                      "#4682B4"
                                  };



            if (segments != null && segments.Count > 0)
            {
                dropdownPercuros.Items.Clear();
                for (int i = 0; i < segments.Count; i++)
                {
                    //PREENCHER DROP DOWN DOS PERCURSOS
                    //peFilterPer.Items.Add(new ListItem("Percurso " + (i + 1), i.ToString()));
                    dropdownPercuros.Items.Add(
                        new ListItem(segments[i].StartDate.ToString("HH:mm") + "-" +
                                     segments[i].EndDate.ToString("HH:mm")));
                    LitLegend.Text += "<p style=color:" + colors[k] + ">" + segments[i].StartDate.ToString("HH:mm") +
                                      "-" + segments[i].EndDate.ToString("HH:mm") + "</p>";

                    k++;
                    if (k >= colors.Length)
                    {
                        k = 0;
                    }
                }
                dropdownPercuros.Items.Insert(0, "Todos");


                k = 0;
                //   body.Attributes.Add("onload", string.Format(ciInv, "initialize();")); 
                //body.Attributes.Add("onload","showLine(overlays,overlaysPolys);");
                sb = new StringBuilder(200*segments.Sum(seg => seg.Coordinates.Length));


                GpsCoordinates lastCoordinate = null;
                for (var j = 0; j < segments.Count; j++)
                {
                    var points = segments[j].Coordinates;
                    //int dez = 0;

                    if (j > 0 && j < segments.Count + 1)
                    {
                        sb.Append("var poly_Red" + j + " = [];");
                        var prev = lastCoordinate;
                        var current = points[0];
                        foreach (var point in new[] {prev, current})
                        {

                            sb.Append(string.Format(ciInv,
                                                    "poly_Red" + j + ".push(new google.maps.LatLng({0}, {1}));\n ",
                                                    point.Latitude, point.Longitude));
                        }

                        sb.AppendLine(string.Format(ciInv,
                                                    "var polyline = new google.maps.Polyline({0}path: poly_Red" + j +
                                                    ", strokeColor: '" + colors[k] +
                                                    "', strokeWeight: 5, strokeOpacity: 1.0{1} );\n", "{", "}"));
                        sb.AppendLine("overlaysPolys.push(polyline);\n");
                        //   sb.AppendLine("polyline.setMap(map_canvas");

                        sb.AppendLine(string.Format(ciInv,
                                                    "var marker" + prev.Id +
                                                    " = new google.maps.Marker({2}icon: orangeIcon, shadow: shadow, position: new google.maps.LatLng({0}, {1}){3});",
                                                    prev.Latitude, prev.Longitude, "{", "}"));
                        sb.AppendLine("google.maps.event.addListener(marker" + prev.Id +
                                      ", 'click', function() {var infowindow = new google.maps.InfoWindow({content: \"<div style=\\\"color: #000000;\\\"><b>Paragem</b><br />Hora Inicio: " +
                                      prev.Timestamp.ToString("dd-MM-yyyy HH:mm:ss") + "<br />Hora Fim: " +
                                      current.Timestamp.ToString("dd-MM-yyyy HH:mm:ss") + "<br />Duraç&atilde;o:" +
                                      new DateTime((current.Timestamp - prev.Timestamp).Ticks).ToString("HH:mm:ss") +
                                      "<br /></div>\"});infowindow.open(map, marker" + prev.Id + ");});");
                        sb.AppendLine(string.Format(ciInv, "overlays.push(marker" + prev.Id + ");"));
                    }
                    sb.Append("var poly_Blue" + j + " = [];");
                    foreach (var point in points)
                    {
                        sb.Append("var lat = new google.maps.LatLng(" + point.Latitude.ToString().Replace(',', '.') +
                                  ", " + point.Longitude.ToString().Replace(',', '.') + ");\n");
                        sb.Append(string.Format(ciInv,
                                                "poly_Blue" + j + ".push(lat);\n"));

                    }

                    lastCoordinate = segments[j].Coordinates.Last();

                    sb.AppendLine(string.Format(ciInv,
                                                "var polyline = new google.maps.Polyline( {0}path: poly_Blue" + j +
                                                ",  strokeColor: '" + colors[k] +
                                                "', strokeWeight:5, strokeOpacity: 1.0{1} );\n", "{", "}"));

                    /*
                     *   var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});

                     */


                    sb.AppendLine("overlaysPolys.push(polyline);\n");
                    //  sb.AppendLine("polyline.setMap('map_canvas'");
                    k++;

                    if (k == colors.Length)
                    {
                        k = 0;
                    }

                }

                var paragens = g.getParagensEspec(int.Parse(dropDownVeiculo.SelectedItem.Value), DateTime.Now.Date,
                                                  DateTime.Now.Date.AddDays(1).AddSeconds(-1));
                foreach (var paragem in paragens)
                {
                    sb.AppendLine(string.Format(ciInv,
                                                "var marker" + paragem.Coordinates.Id +
                                                " = new google.maps.Marker({2}icon: blueIcon, shadow: shadow, position: new google.maps.LatLng({0}, {1}){3});",
                                                paragem.Coordinates.Latitude, paragem.Coordinates.Longitude, "{", "}"));
                    sb.AppendLine("google.maps.event.addListener(marker" + paragem.Coordinates.Id +
                                  ", 'click', function() {var infowindow = new google.maps.InfoWindow({content: \"<div style=\\\"color: #000000;\\\"><b>Paragem</b><br />Hora Inicio: " +
                                  paragem.Coordinates.Timestamp.ToString("dd-MM-yyyy HH:mm:ss") + "<br />Hora Fim: " +
                                  paragem.CoordinatesFim.Timestamp.ToString("dd-MM-yyyy HH:mm:ss") +
                                  "<br />Duraç&atilde;o:" +
                                  new DateTime((paragem.CoordinatesFim.Timestamp - paragem.Coordinates.Timestamp).Ticks)
                                      .ToString("HH:mm:ss") + "<br /></div>\"});infowindow.open(map, marker" +
                                  paragem.Coordinates.Id + ");});");
                    sb.AppendLine(string.Format(ciInv, "overlays.push(marker" + paragem.Coordinates.Id + ");"));
                }

                var firstPoint = segments.First().Coordinates.First();
                var lastPoint = segments.Last().Coordinates.Last();
                sb.AppendLine(
                    "var markerIni = new google.maps.Marker({ icon: greenIcon, shadow: shadow,clickable: false, position: new google.maps.LatLng(" +
                    firstPoint.Latitude.ToString().Replace(',', '.') + "," +
                    firstPoint.Longitude.ToString().Replace(',', '.') + ") });");
                sb.AppendLine("overlays.push(markerIni);");
                sb.AppendLine(
                    "var markerFim = new google.maps.Marker({ icon: redIcon, shadow: shadow,clickable: false, position: new google.maps.LatLng(" +
                    lastPoint.Latitude.ToString().Replace(',', '.') + "," +
                    lastPoint.Longitude.ToString().Replace(',', '.') + ") });");
                sb.AppendLine("overlays.push(markerFim);");
                sb.AppendLine("showLine(overlays, overlaysPolys)");
                litBuildPoly.Text = sb.ToString();
                // lblInformation.Visible = false;

                LoadMap = true;
            } else
            {
                sb.AppendLine("doStuff();");
                litBuildPoly.Text = sb.ToString();
            }

        }

           
        


        protected void percursoDropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
    }
}